package com.heatup.apt.management.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heatup.apt.common.util.JsonUtils;
import com.heatup.apt.common.util.OssFileUtil;
import com.heatup.apt.management.service.DataDictService;
import com.heatup.apt.management.service.coach.CoachService;
import com.heatup.apt.management.service.store.StoreService;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.store.StoreInfoRequest;

/**
 * Created by b3st9u on 16/8/22.
 * Updated by blank on 16/10/8.+
 */
@Controller
@RequestMapping("system/store")
public class StoreController extends BaseController {
	
    private final static Logger log = LoggerFactory.getLogger(StoreController.class);


    @Autowired
    private StoreService storeService;

    @Autowired
    private CoachService coachService;
    
    @Autowired
    private DataDictService dataDictService;



    /**
     * 门店管理新增
     *
     * @return 跳转到门店新增页面
     */
    @RequestMapping(value = "to_store_add", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toStoreAdd() {

        ModelAndView modelAndView = new ModelAndView("store/store-add");
        List<DataDict> userHasSerivceList = dataDictService.queryDataDicts("USER_HAS_SERVICE");
        List<DataDict> userNotSerivceList = dataDictService.queryDataDicts("USER_NOT_SERVICE");
        modelAndView.addObject("coachList", coachService.queryAllCoachInfo());
        modelAndView.addObject("userHasSerivceList", userHasSerivceList);
        modelAndView.addObject("userNotSerivceList", userNotSerivceList);
        return modelAndView;
    }

    /**
     * 跳转到门店编辑
     *
     * @param id 门店 ID
     * @return 门店编辑
     */
    @RequestMapping(value = "/to_store_edit", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toStoreEdit(@RequestParam Long id) {

        ModelAndView modelAndView = new ModelAndView("store/store-edit");
        List<DataDict> userHasSerivceList = dataDictService.queryDataDicts("USER_HAS_SERVICE");
        List<DataDict> userNotSerivceList = dataDictService.queryDataDicts("USER_NOT_SERVICE");
        modelAndView.addObject("coachList", coachService.queryAllCoachInfo());
        StoreInfoRequest s = storeService.queryStoreInfoById(id);
        modelAndView.addObject("store", s);
        modelAndView.addObject("storeJson", JsonUtils.obj2Json(s));
        modelAndView.addObject("userHasSerivceList", userHasSerivceList);
        modelAndView.addObject("userNotSerivceList", userNotSerivceList);
        return modelAndView;
    }

    /**
     * 门店保存
     *
     * @param storeInfoRequest 门店信息
     * @return 保存结果
     */
    @RequestMapping(value = "/store_save", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String save(StoreInfoRequest storeInfoRequest){

        if (storeInfoRequest == null) {
            return "false";
        }
        boolean success = storeService.saveStore(storeInfoRequest);
        if (success) {
            return "success";
        }
        return "false";
    }

    /**
     * 门店删除
     *
     * @param storeInfo 门店
     * @return 删除结果
     */
    @RequestMapping(value = "/store_delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String storeDelete(StoreInfo storeInfo){

        String result ="删除失败";
        if (storeInfo == null || storeInfo.getId() == null) {
            return result;
        }
        boolean success = storeService.delStoreInfoById(storeInfo.getId());
        if (success) {
            result = "删除成功";
        }
        return result;
    }

    /**
     * 门店开业
     *
     * @param storeInfo 门店ID
     * @return
     */
    @RequestMapping(value = "/store_open", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String storeOpen(StoreInfo storeInfo){

        String result ="开业失败";
        if (storeInfo == null || storeInfo.getId() == null) {
            return result;
        }
        boolean success = storeService.openStoreById(storeInfo);
        if (success) {
            storeInfo = storeService.queryStoreInfoById(storeInfo.getId().longValue());
            log.info( storeInfo.getId() + storeInfo.getStoreName() + "门店开业成功");
            result = "开业成功";
        }
        return result;
    }


    /**
     * 门店停业
     *
     * @param storeInfo 门店 ID
     * @return 停业结果
     */
    @RequestMapping(value = "/store_close", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String storeClose(StoreInfo storeInfo){

        String result ="开业失败";
        if (storeInfo == null || storeInfo.getId() == null) {
            return result;
        }
        boolean success = storeService.closeStoreById(storeInfo);
        if (success) {
            result = "开业成功";
        }
        return result;
    }

    /**
     * 门店即将开业
     *
     * @param storeInfo 门店 ID
     * @return 开业结果
     */
    @RequestMapping(value = "/store_ready", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String storeReady(StoreInfo storeInfo){

        String result ="即将开业失败";
        if (storeInfo == null || storeInfo.getId() == null) {
            return result;
        }
        boolean success = storeService.readyStoreById(storeInfo);
        if (success) {
            result = "即将开业成功";
        }
        return result;
    }




    /**
     * 跳转门店列表
     *
     * @return 门店列表页面
     */
    @RequestMapping(value = "/to_store_list", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView list2(){

        return new ModelAndView("store/store-list");
    }

    /**
     * 门店列表分页
     */
    @RequestMapping(value = "/store_list")
    public void storeList(HttpServletResponse response,
                          @RequestParam int pageIndex,
                          @RequestParam int pageSize,
                          @RequestParam(required = false) String storeName,
                          @RequestParam(required = false) String province,
                          @RequestParam(required = false) String city,
                          @RequestParam(required = false) String area,
                          @RequestParam(required = false) Integer status
                          ){

        if (pageIndex > 0)
            --pageIndex;
        if (pageSize <=0)
            pageSize = 10;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("pageIndex", pageIndex);
        paramsMap.put("pageSize", pageSize);
        paramsMap.put("storeName", storeName);
        paramsMap.put("province", province);
        paramsMap.put("city", city);
        paramsMap.put("area", area);
        paramsMap.put("status", status);

        Map<String, Object> map = storeService.queryStoreList(paramsMap);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("storeList", map.get("storeList"));
        jsonObject.put("storeCount", map.get("storeCount"));
        responseSendMsg(response, jsonObject.toString());

    }

    @RequestMapping(value = "/upload_oss_param", method = {RequestMethod.GET, RequestMethod.POST})
    public void upload_oss_param(HttpServletResponse response) throws IOException {
    	Map<String, String> map = OssFileUtil.getOSSParam();
    	responseSendMsg(response, JSON.toJSONString(map));
    }
    
    
//    /**
//     * 图片上传
//     * @param image
//     * @param response
//     */
//    @RequestMapping(value = "/upload_pic")
//    public void upload_pic(@RequestParam("file") MultipartFile image, HttpServletResponse response) throws IOException {
//		JSONObject jsonObject = new JSONObject();
//		try {
//			if (!image.isEmpty()) {
//				jsonObject.put("error", false);
//				File tempDir = new File(TEMP_DIR);
//				if (!tempDir.exists()) {
//					if (!tempDir.isDirectory()) {
//						tempDir.mkdir();
//					}
//				}
//				File file = new File(TEMP_DIR + image.getOriginalFilename());
//				image.transferTo(file);
//				String fileExt = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf("."));
//				String imagePath = OssFileUtil.uploadFile(file.getPath(),
//						UUID.randomUUID().toString().substring(0, 8) + fileExt);
//				jsonObject.put("url", imagePath);
//				responseSendMsg(response, jsonObject.toJSONString());
//			} else {
//				jsonObject.put("error", true);
//				jsonObject.put("url", "");
//				responseSendMsg(response, jsonObject.toJSONString());
//			}
//		} catch (Exception ex) {
//			logger.error("StoreController upload method error! " + ex.getMessage() + ex.toString());
//		}
//    }


//    /**
//     * 删除图片
//     * @param fileName
//     */
//    @RequestMapping(value = "/delete_pic")
//    @ResponseBody
//    public String deleteImg(@RequestParam String fileName){
//
//        OssFileUtil.deleteFile(fileName);
//
//        return fileName;
//    }
}
